<template>
  <div class="header">
    <div class="left">
      <img class="logo" src="../../assets/images/logo.png" alt="" />
    </div>
    <div class="mid">
      <n-menu class="menu" v-model:value="activeKey" mode="horizontal" :options="menuOptions" @click="routerPlace" />
    </div>
    <div class="right">
      <el-popover class="box-item" placement="bottom" popper-class="no-padding" trigger="click" width="300" :offset="0"
        :show-arrow="false">
        <template #reference>
          <div class="work-center" v-if="$store.oj.isLogin">任务中心</div>
        </template>
        <div class="task" v-if="userTaskList.length > 0">
          <div class="task-header">任务列表</div>
          <div class="task-list">
            <div class="task-item" v-for="(item, index) in userTaskList" :key="item.id">
              <taskItem :taskInfo="item" @lookTask="lookTask"></taskItem>
            </div>
          </div>
        </div>
        <div v-else class="empty-task">暂无任务</div>
      </el-popover>
      <div class="avator" v-show="!$store.oj.isLogin" @click="this.isShowLogin = true">
        <el-avatar> 登录 </el-avatar>
      </div>
      <el-dropdown trigger="click" class="dropdown" v-show="$store.oj.isLogin">
        <div class="avator">
          <el-badge is-dot :hidden="$store.oj.discuss.getNoReadNoticeNum === 0" class="notice-num">
            <el-avatar v-if="
              $store.oj.userData.avatar === null ||
              $store.oj.userData.avatar === ''
            ">
              <img src="@/assets/images/defaultHeader.jpg" alt="" />
            </el-avatar>
            <el-avatar v-else :src="$store.oj.getUserAvatar"></el-avatar>
          </el-badge>
        </div>
        <template #dropdown>
          <el-dropdown-menu class="dropMenu" popper-class="demo">
            <el-dropdown-item @click="handlerToUserInfo()">个人信息</el-dropdown-item>
            <el-dropdown-item @click="handlerToUserNotice()">
              <el-badge class="badge" :hidden="$store.oj.discuss.getNoReadNoticeNum === 0"
                :value="$store.oj.discuss.getNoReadNoticeNum" :max="99">个人通知</el-badge>
            </el-dropdown-item>
            <el-dropdown-item v-if="$store.oj.premission.includes('web:front:toManage')"
              @click="handlerToAdmin()">后台管理</el-dropdown-item>
            <el-dropdown-item @click="userLogOut()">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 登录弹框 -->
    <n-modal v-model:show="isShowLogin">
      <n-card :bordered="false" role="dialog" aria-modal="true" class="loginCard">
        <transition>
          <div class="login" v-if="!isRegister">
            <div class="toRegistry" @click="this.isRegister = true">
              去注册 >
            </div>
            <img class="logo" src="../../assets/images/logo.png" alt="" />
            <div class="card-body">
              <n-form ref="loginForm" :rules="rules" :model="userData" class="nForm">
                <n-form-item path="account" class="nFormItem">
                  <n-input class="textInput" v-model:value="userData.account" type="text" :placeholder="loginWay"
                    clearable maxlength="20">
                    <template #prefix>
                      <div>
                        <i class="iconfont icon-zhanghao-" v-show="userData.loginType === 0"></i>
                        <i class="iconfont icon-shoujidenglu" v-show="userData.loginType === 1"></i>
                        <i class="iconfont icon-youxiang1" v-show="userData.loginType === 2"></i>
                      </div>
                    </template>
                    <template #suffix>
                      <n-popselect v-model:value="userData.loginType" :options="loginOptions" trigger="click">
                        <n-button class="loginWay-btn" type="tertiary">
                          <i class="iconfont icon-diandian"></i>
                        </n-button>
                      </n-popselect>
                    </template>
                  </n-input>
                </n-form-item>

                <n-form-item path="password" class="nFormItem">
                  <n-input class="textInput" v-model:value="userData.password" type="password" placeholder="密码"
                    clearable show-password-on="mousedown" maxlength="20">
                    <template #prefix>
                      <i class="iconfont icon-mima"></i>
                    </template>
                  </n-input>
                </n-form-item>

                <n-form-item path="code" class="nFormItem">
                  <n-input class="vertifyCode" v-model:value="userData.code" type="text" placeholder="验证码" clearable
                    maxlength="8" @keydown.enter="userLogin()">
                    <template #prefix>
                      <i class="iconfont icon-icon_xinyong_xianxing_jijin-295"></i>
                    </template>
                  </n-input>
                  <el-image class="elImage" :src="'data:image/png;base64,' + base64ImgCode"
                    @click="getCode()"></el-image>
                </n-form-item>
              </n-form>
            </div>
            <div class="card-footer">
              <n-button class="n-btn" type="success" @click="userLogin()">登录</n-button>
            </div>
          </div>
        </transition>
        <transition>
          <div class="register" v-if="isRegister && allowRegistry">
            <div class="toRegistry" @click="this.isRegister = false">
              去登录 >
            </div>
            <img class="logo" src="../../assets/images/logo.png" alt="" />
            <div class="card-body">
              <n-form ref="loginForm" :rules="rules" :model="userData" class="nForm">
                <n-form-item path="username" class="nFormItem">
                  <n-input class="textInput" v-model:value="userData.username" type="text" :placeholder="loginWay"
                    clearable maxlength="20">
                    <template #prefix>
                      <i class="iconfont icon-zhanghao-"></i>
                    </template>
                  </n-input>
                </n-form-item>

                <n-form-item path="password" class="nFormItem">
                  <n-input class="textInput" v-model:value="userData.password" type="password" placeholder="密码"
                    clearable show-password-on="mousedown" maxlength="20">
                    <template #prefix>
                      <i class="iconfont icon-mima"></i>
                    </template>
                  </n-input>
                </n-form-item>

                <n-form-item path="password2" class="nFormItem">
                  <n-input class="textInput" v-model:value="userData.password2" type="password" placeholder="确认密码"
                    show-password-on="mousedown" clearable maxlength="20">
                    <template #prefix>
                      <i class="iconfont icon-mima"></i>
                    </template>
                  </n-input>
                </n-form-item>

                <n-form-item path="code" class="nFormItem">
                  <n-input class="vertifyCode" v-model:value="userData.code" type="text" placeholder="验证码" clearable
                    maxlength="8" @keydown.enter="userRegister()">
                    <template #prefix>
                      <i class="iconfont icon-icon_xinyong_xianxing_jijin-295"></i>
                    </template>
                  </n-input>
                  <el-image class="elImage" :src="'data:image/png;base64,' + base64ImgCode"
                    @click="getCode()"></el-image>
                </n-form-item>
              </n-form>
            </div>
            <div class="card-footer">
              <n-button class="n-btn" type="success" @click="userRegister()">注册</n-button>
            </div>
          </div>
        </transition>
      </n-card>
    </n-modal>

    <n-modal v-model:show="isShowLogining" :close-on-esc="false">
      <rocketVue></rocketVue>
    </n-modal>
  </div>
</template>

<script>
import { h } from "vue"
import {
  userLoginAPI,
  userRegisterAPI,
  userInfoAPI,
  userLogOutAPI,
  getTaskListAPI,
} from "@/api/ojAPI/ojAPI"
import { getSettingRegistryAPI } from "@/pages/adminPage/setting/api/index"
import { ElMessage } from "element-plus"
import axios from "axios"
import bus from "vue3-eventbus"
import rocketVue from "@/components/publicComponents/rocket.vue"
import taskItem from "@/components/ojComponents/taskItem/taskItem.vue"
import taskDialog from "@/components/ojComponents/taskItem/taskDialog.vue"
export default {
  data () {
    return {
      activeKey: null,
      isShowLogining: false,
      menuOptions: [
        {
          label: this.renderIcon("icon-home", "首页"),
          key: "homepage",
        },
        {
          label: this.renderIcon("icon-bisaihuodong", "比赛"),
          key: "race",
        },
        {
          label: this.renderIcon("icon-jiugongge", "题库"),
          key: "bank",
        },
        {
          label: this.renderIcon("icon-shijuan-xianxing", "训练"),
          key: "training",
        },
        {
          label: this.renderIcon("icon-shujukanban", "评测"),
          key: "evaluation",
        },
        {
          label: this.renderIcon("icon-paiming", "排名"),
          key: "ranking",
        },
        {
          label: this.renderIcon("icon-xiaoxi", "讨论"),
          key: "discuss",
        },
        {
          label: this.renderIcon("icon-jubao", "关于"),
          key: "us",
        },
      ],
      isLogin: false,
      isShowLogin: false,
      userData: {
        username: null,
        account: null,
        phone: null,
        email: null,
        password: null,
        password2: null,
        code: null,
        loginType: 0,
        uuid: null,
      },
      rules: {
        username: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error("请输入账户")
              }
              return true
            },
            trigger: ["input", "blur"],
          },
        ],
        account: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error("请输入账号")
              }
              return true
            },
            trigger: ["input", "blur"],
          },
        ],
        phone: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error("请输入手机号")
              }
              return true
            },
            trigger: ["input", "blur"],
          },
        ],
        email: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error("请输入邮箱")
              }
              return true
            },
            trigger: ["input", "blur"],
          },
        ],
        password: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error("请输入密码")
              }
              return true
            },
            trigger: ["input", "blur"],
          },
        ],
        password2: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error("请输入确认密码")
              }
              return true
            },
            trigger: ["input", "blur"],
          },
        ],
        code: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error("请输入验证码")
              }
              return true
            },
            trigger: ["input", "blur"],
          },
        ],
      },
      loginOptions: [
        {
          label: "账号登录",
          value: 0,
        },
        {
          label: "手机号登录",
          value: 1,
        },
        {
          label: "邮箱登录",
          value: 2,
        },
      ],
      loginForm: null,
      isRegister: false,
      base64ImgCode: null,
      noticeValue: 100,
      allowRegistry: true,
      userTaskList: [],
      intervalTime: null,
      timer: null
    }
  },
  created () {
    bus.on("showLoginDialog", () => {
      this.isShowLogin = true
    })
    bus.on("getUserTask", () => {
      this.getUserTask()
    })
  },
  mounted () {
    this.getCode()
    this.getSettingRegistry()
  },
  unmounted () {
    clearTimeout()
    clearInterval()
  },
  methods: {
    renderIcon (className, name) {
      return () => h("i", { class: [className, "iconfont"] }, "", name)
    },
    // 用户登录
    userLogin () {
      if (this.userData.loginType == 0) {
        if (!this.userData.account) {
          ElMessage.error("请输入账号")
          return
        }
      } else if (this.userData.loginType == 1) {
        if (!this.userData.phone) {
          ElMessage.error("请输入手机号")
          return
        }
      } else {
        if (!this.userData.email) {
          ElMessage.error("请输入邮箱")
          return
        }
      }
      if (this.userData.password.length == 0) {
        ElMessage.error("请输入密码")
        return
      }
      if (this.userData.code.length == 0) {
        ElMessage.error("请输入验证码")
        return
      }
      this.isShowLogining = true
      userLoginAPI(this.userData)
        .then((res) => {
          if (res.data.code === 200) {
            this.$router.go(0)
            localStorage.setItem("TOKEN", res.data.data)
            this.$store.oj.updateIsLogin(true)
            this.clearParams()
            this.getUserInfo()
            this.isShowLogin = false
            this.isShowLogining = false
            ElMessage.success("登录成功")
          } else {
            this.getCode()
          }
          this.isShowLogining = false
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 用户注册
    async userRegister () {
      await userRegisterAPI(this.userData)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success("注册成功")
            this.isRegister = false
            this.clearParams()
          }
          this.getCode()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取验证码
    async getCode () {
      const token = localStorage.getItem("TOKEN")
      if (!token) {
        sessionStorage.clear()
        await axios
          .get(null, {
            baseURL: `${import.meta.env.VITE_APP_URL}/code`,
          })
          .then((res) => {
            if (res.data.code === 200) {
              this.base64ImgCode = res.data.data.img
              this.userData.uuid = res.data.data.uuid
            }
          })
          .catch((err) => {
            ElMessage.success("获取验证码失败")
          })
      }
    },
    //获取用户信息
    async getUserInfo () {
      await userInfoAPI()
        .then((res) => {
          if (res.data.code === 200) {
            this.$store.oj.updateUserData(res.data.data)
            this.getUserTask()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //重置表单
    clearParams () {
      this.userData.account = null
      this.userData.password = null
      this.userData.password2 = null
      this.userData.username = null
      this.userData.code = null
    },
    // 用户登出
    async userLogOut () {
      this.isShowLogining = true
      await userLogOutAPI()
        .then((res) => {
          if (res.data.code === 200) {
            this.$store.oj.clearUserData()
            localStorage.clear()
            sessionStorage.clear()
            this.$router.push({
              path: "/home/homepage",
            })
            this.getCode()
            this.isShowLogining = false
            ElMessage.success("登出成功")
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //获取用户任务列表
    async getUserTask () {
      if (!localStorage.getItem("TOKEN")) {
        return
      }
      try {
        const response = await getTaskListAPI()
        const { code, data, msg } = response.data
        if (code == 200) {
          this.userTaskList = data
          setTimeout(async () => {
            await this.getUserTask()
          }, 5000)
        }
      } catch (err) {
        console.log(err)
      }
    },
    //路由跳转
    routerPlace () {
      this.$router.replace({
        path: `/home/${this.activeKey}`,
      })
    },
    handlerToUserInfo () {
      this.$router.push({
        path: "/home/userInfo/info",
      })
    },
    handlerToUserNotice () {
      this.$router.push({
        path: "/home/notice/discuss",
      })
    },
    handlerToAdmin () {
      window.open(`http://${window.location.host}/#/admin/dashboard`)
    },
    // 是否允许注册
    getSettingRegistry () {
      getSettingRegistryAPI().then((res) => {
        this.allowRegistry = res.data.data
      })
    },
    lookTask (data) {
      this.$emit("lookTask", data)
    },
  },
  watch: {
    $route: {
      handler: function (newV) {
        if (newV != undefined) {
          this.activeKey = this.$route.name
        }
      },
      //双向绑定
      immediate: true,
    },
  },
  computed: {
    loginWay () {
      switch (this.userData.loginType) {
        case 0:
          return "账号"
        case 1:
          return "手机号"
        case 2:
          return "邮箱"
        default:
          break
      }
    },
  },
  components: {
    rocketVue,
    taskItem,
    taskDialog,
  },
}
</script>

<style lang="less" scoped>
.header {
  width: 100%;
  height: 60px;
  line-height: 60px;
  display: flex;
  border-radius: 10px 10px 0 0;
  backdrop-filter: saturate(80%) blur(80px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.15);

  .left {
    height: 54px;
    width: 14%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: auto 0;
    font-weight: 550;
    font-size: 18px;
    color: #666;
    user-select: none;

    .logo {
      width: auto;
      height: 54px;
      margin-right: 5px;
    }
  }

  .mid {
    height: 60px;
    line-height: 60px;
    width: 70%;
    display: flex;
    justify-content: space-between;
    color: #888;
    font-size: 12px;

    .menu {
      height: 35px;
      line-height: 35px;
      margin: auto 0;
    }
  }

  .right {
    height: 60px;
    width: 15%;
    display: flex;
    margin-left: auto;

    .work-center {
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .avator {
      margin: auto;
      cursor: pointer;
    }

    .dropdown {
      margin-left: 20px;
    }

    .notice {
      align-items: center;
      cursor: pointer;
      display: flex;
      border: none !important;

      .notice-link {
        font-size: 1.3em;
      }
    }
  }
}

.loginCard {
  border-radius: 20px;
  overflow: hidden;
  width: 400px;
  height: 550px;
  display: flex;

  .textInput {
    overflow: hidden;
  }

  ::v-deep(.n-card__content) {
    padding: 6px 30px 10px 30px;
    display: flex;
    flex-direction: column;
  }

  .logo {
    width: 46%;
    margin-top: 6%;
    margin-left: auto;
    margin-right: auto;
  }

  .toRegistry {
    text-align: right;
    cursor: pointer;
    color: #888;
    font-weight: bold;
    position: relative;
    right: -5px;
  }

  .login {
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;

    .card-body {
      .nForm {
        display: flex;
        flex-direction: column;
        height: 100%;

        .nFormItem {
          height: 25%;

          .loginWay-btn {
            position: relative;
            left: 15px;
          }

          .vertifyCode {
            width: calc(70% - 10px);
            margin-right: 10px;
          }

          .elImage {
            width: 30%;
            height: 100%;
            line-height: 100%;
            border-radius: 20px;
            border: 2px solid #999;
            margin: auto;
            overflow: hidden;
          }
        }
      }
    }
  }

  .card-footer {
    display: flex;
    margin: auto 0 20px 0;

    .n-btn {
      width: 100%;
    }
  }

  .checkBox {
    width: 100%;
    height: 40%;
    line-height: 40%;
    background-color: rgba(71, 168, 98, 0.8);
    clip-path: polygon(40% 100%, 100% 100%, 100% 0%);
    text-align: right;
    border-radius: 0 0 50% 0;

    &:active {
      background-color: rgba(71, 168, 98);
      transform: translate(20px);
      transition: 0.5s;
    }

    .text {
      font-size: 16px;
      color: #ffffff;
      font-weight: 600;
      margin-right: 20px;
      position: relative;
      top: 35%;
    }
  }

  .register {
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;

    ::v-deep(.n-form-n-form-item-feedback-wrapper) {
      height: 0 !important;
    }

    .card-body {
      height: 46%;

      .nForm {
        display: flex;
        flex-direction: column;
        height: 100%;

        .nFormItem {
          height: 25%;

          .loginWay-btn {
            position: relative;
            left: 15px;
          }

          .vertifyCode {
            width: calc(70% - 10px);
            margin-right: 10px;
          }

          .elImage {
            width: 30%;
            height: 100%;
            line-height: 100%;
            border-radius: 20px;
            border: 2px solid #999;
            margin: auto;
            overflow: hidden;
          }
        }
      }
    }

    .checkBox {
      width: 100%;
      height: 40%;
      line-height: 40%;
      background-color: rgba(71, 168, 98, 0.8);
      clip-path: polygon(40% 100%, 100% 100%, 100% 0%);
      text-align: right;

      &:active {
        background-color: rgba(71, 168, 98);
        transform: translate(20px);
        transition: 0.5s;
      }

      .text {
        font-size: 16px;
        color: #ffffff;
        font-weight: 600;
        margin-right: 20px;
        position: relative;
        top: 35%;
      }
    }
  }
}

.card {
  width: 50vw;
  height: 50vh;
  background-color: #fff;
}

.v-enter-from {
  transform: translate(-200px);
  opacity: 0;
}

.v-enter-active {
  transition: 0.5s;
  transition-delay: 0.5s;
}

.v-enter-to {
  transform: translate(0);
  opacity: 1;
}

.v-leave-from {
  transform: translate(0);
  opacity: 1;
}

.v-leave-active {
  transition: 0.2s;
}

.v-leave-to {
  transform: translate(200px);
  opacity: 0;
}

::v-deep(.el-badge) {
  --el-badge-font-size: 9px !important;
  --el-badge-padding: 3px !important;
  --el-badge-size: 15px !important;
}

.notice-num {
  ::v-deep(.el-badge__content.is-fixed) {
    top: 4px;
  }

  ::v-deep(.el-badge__content.is-fixed.is-dot) {
    right: 7px;
  }
}

::v-deep(.iconfont):hover {
  color: @menuHoverColor !important;
  font-weight: 550 !important;
}

::v-deep(.n-menu.n-menu--horizontal .n-menu-item-content.n-menu-item-content--selected .n-menu-item-content-header) {
  color: @menuHoverColor !important;
  font-weight: 550 !important;
  font-family: "Arial" !important;
}

::v-deep(.n-menu) {
  --n-item-text-color-hover-horizontal: @menuColor !important;
  --n-item-text-color: @menuColor !important;
  font-weight: 550;
  font-family: "Arial" !important;
}

::v-deep(.el-badge) {
  --el-badge-padding: 4px !important;
  --el-badge-size: 14px !important;
  font-family: "Arial" !important;
}
</style>
